<template>
  <ion-page>
    <ion-toolbar>
      <div class="user-header">
        <ion-avatar class="user-avatar">
          <ion-icon style="font-size: 70px" :icon="personCircleOutline"/>
        </ion-avatar>
        <div class="user-info">
          <h2>{{ userInfo.realNameForChinese || '未命名用户' }}</h2>
          <p>{{ userInfo.loginName }}</p>
          <p>{{ roleInfo.displayRoleName }}</p>
        </div>
      </div>
    </ion-toolbar>
    <ion-content class="ion-padding content-container">
      <ion-list> 
        <ion-item>
          <ion-toggle 
            v-model="fsOpen"
            @ionChange="handleNotificationToggle('fsOpen')"
            :disabled="loading"
          >
            Feishu Notification
          </ion-toggle>
        </ion-item>        
        <ion-item>
          <ion-toggle 
            v-model="ddOpen"
            @ionChange="handleNotificationToggle('ddOpen')"
            :disabled="loading"
          >
            DingTalk Notification
          </ion-toggle>
        </ion-item>
        <ion-item>
          <ion-toggle 
            v-model="qywxOpen"
            @ionChange="handleNotificationToggle('qywxOpen')"
            :disabled="loading"
          >
            WeCom Notification
          </ion-toggle>
        </ion-item>
        <ion-item>
          <ion-toggle 
            v-model="notificationEnabled"
            @ionChange="handleNotificationToggle('notificationEnabled')"
            :disabled="loading"
          >
            Sync Filter Notification
          </ion-toggle>
          <ion-spinner v-if="loading" name="crescent"></ion-spinner>
        </ion-item>
      </ion-list>
    </ion-content>
    <ion-footer class="ion-padding">
      <ion-button 
        expand="block" 
        color="danger"
        @click="logout"
      >
        <ion-icon :icon="logOutOutline" slot="start"/>
        Exit
      </ion-button>
    </ion-footer>
  </ion-page>
</template>

<script setup>
import { 
  logOutOutline, 
  personCircleOutline
} from 'ionicons/icons';
import { 
  IonPage,
  IonToolbar,
  IonIcon,
  IonContent,
  IonButton,
  IonAvatar,
  IonFooter,
  IonList,
  IonItem,
  IonToggle,
  IonSpinner,
  onIonViewWillEnter
} from '@ionic/vue';
import { getCurrentInstance } from 'vue';
import { ref, onMounted } from 'vue';
import axios from 'axios';
import services from '@/api/test'
const { proxy } = getCurrentInstance();

const userInfo = ref({
  loginName: '',
  realNameForChinese: '',
});

const roleInfo = ref({
  displayRoleName: ''
});

const notificationEnabled = ref(false);
const fsOpen = ref(true);
const ddOpen = ref(true);
const qywxOpen = ref(true);
const loading = ref(false);

const logout = () => {
  proxy.$user.logout();
};

const fetchUserInfo = async () => {
  try {
    const accessToken = localStorage.getItem('accessToken');
    const response = await axios.get('https://www.svom-gwacn.cn/svomUPMS/user/profile', {
      params: {
        accessToken: accessToken
      },
      headers: { Authorization: `Bearer ${accessToken}` }
    });
    
    userInfo.value = {
      loginName: response.data.data.userInfo.loginName,
      realNameForChinese: response.data.data.userInfo.realNameForChinese,
    };

    roleInfo.value = {
      displayRoleName: localStorage.getItem('displayRoleName') || ''
    };
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
};

const fetchNotificationSettings = async () => {
  try {
    loading.value = true;
    const userId = localStorage.getItem('userId');
    
    // 优先从后端获取设置
    const response = await services.get('/api/settings', {
      headers: {
        'X-User-Id': userId,
        'Cache-Control': 'no-cache'
      }
    });
    
    if (response.data) {
      notificationEnabled.value = response.data.notificationEnabled ?? false;
      fsOpen.value = response.data.fs_open ?? true;
      ddOpen.value = response.data.dd_open ?? true;
      qywxOpen.value = response.data.qywx_open ?? true;
      
      // 同步到本地存储
      localStorage.setItem('userSettings', JSON.stringify({
        notificationEnabled: notificationEnabled.value,
        fsOpen: fsOpen.value,
        ddOpen: ddOpen.value,
        qywxOpen: qywxOpen.value
      }));
    } else {
      // 如果后端没有数据，使用默认值
      setDefaultSettings();
    }
  } catch (error) {
    console.error('获取通知设置失败:', error);
    // 如果接口失败，检查本地是否有存储
    const localSettings = localStorage.getItem('userSettings');
    if (localSettings) {
      const settings = JSON.parse(localSettings);
      notificationEnabled.value = settings.notificationEnabled ?? false;
      fsOpen.value = settings.fsOpen ?? true;
      ddOpen.value = settings.ddOpen ?? true;
      qywxOpen.value = settings.qywxOpen ?? true;
    } else {
      // 如果本地也没有，使用默认值
      setDefaultSettings();
    }
  } finally {
    loading.value = false;
  }
};

const setDefaultSettings = () => {
  notificationEnabled.value = false;
  fsOpen.value = true;
  ddOpen.value = true;
  qywxOpen.value = true;
};

const saveNotificationSettings = async (field) => {
  try {
    loading.value = true;
    const userId = localStorage.getItem('userId');
    
    // 准备要保存的数据
    const settingsData = {
      notificationEnabled: notificationEnabled.value,
      fsopen: fsOpen.value,
      ddopen: ddOpen.value,
      qywxopen: qywxOpen.value
    };
    
    // 直接保存到后端
    await services.post('/api/settings', settingsData, {
      headers: {
        'X-User-Id': userId,
        'Content-Type': 'application/json'
      }
    });
    
    // 成功后更新本地存储
    localStorage.setItem('userSettings', JSON.stringify({
      notificationEnabled: notificationEnabled.value,
      fsOpen: fsOpen.value,
      ddOpen: ddOpen.value,
      qywxOpen: qywxOpen.value
    }));
    
  } catch (error) {
    console.error('保存通知设置失败:', error);
    // 恢复之前的状态
    switch(field) {
      case 'notificationEnabled':
        notificationEnabled.value = !notificationEnabled.value;
        break;
      case 'fsOpen':
        fsOpen.value = !fsOpen.value;
        break;
      case 'ddOpen':
        ddOpen.value = !ddOpen.value;
        break;
      case 'qywxOpen':
        qywxOpen.value = !qywxOpen.value;
        break;
    }
    // 尝试从本地获取最新状态
    const localSettings = localStorage.getItem('userSettings');
    if (localSettings) {
      const settings = JSON.parse(localSettings);
      notificationEnabled.value = settings.notificationEnabled ?? false;
      fsOpen.value = settings.fsOpen ?? true;
      ddOpen.value = settings.ddOpen ?? true;
      qywxOpen.value = settings.qywxOpen ?? true;
    }
  } finally {
    loading.value = false;
  }
};

const handleNotificationToggle = (field) => {
  saveNotificationSettings(field);
};

onIonViewWillEnter(() => {
  fetchNotificationSettings();
});

onMounted(() => {
  fetchUserInfo();
  fetchNotificationSettings();
});
</script>

<style scoped>
.user-header {
  display: flex;
  align-items: center;
  padding: 20px;
}

.user-avatar {
  width: 80px;
  height: 80px;
  margin-right: 20px;
}

.user-info h2 {
  margin: 0;
  font-size: 1.5rem;
}

.user-info p {
  margin: 5px 0;
  color: #666;
}

.content-container {
  --padding-bottom: 80px;
}

ion-item {
  --padding-start: 0;
}

ion-toggle {
  --background: #e1e1e1;
  --background-checked: var(--ion-color-primary);
  --handle-background: #ffffff;
  --handle-background-checked: #ffffff;
  padding: 12px 16px;
}

ion-spinner {
  margin-left: 10px;
}
</style>